package fr.com.drschizzo.raycaster.server;

import java.io.IOException;
import websocket4j.server.WebServerSocket;
import websocket4j.server.WebSocket;

public class Server extends Thread
{

	private WebSocket	ws;

	public Server(WebSocket ws)
	{
		this.ws = ws;
	}

	private void handleConnection()
	{
		try
		{
			while (true)
			{
				String message = ws.getMessage();
				ws.sendMessage(message);
				System.out.println("Received: " + message);
				if (message.equals("exit"))
					break;
			}
		}
		catch (IOException e)
		{
		}
		finally
		{
			try
			{
				ws.close();
			}
			catch (IOException e)
			{
			}
		}
	}

	public void run()
	{
		handleConnection();
	}

	public static void main(String[] args) throws IOException
	{
		WebServerSocket socket = new WebServerSocket(5555);
		try
		{
			while (true)
			{
				WebSocket ws = socket.accept();
				System.out.println("GET " + ws.getRequestUri());
				if (ws.getRequestUri().equals("/echo"))
					(new Server(ws)).start();
				else
				{
					System.out.println("Unsupported Request-URI");
					try
					{
						ws.close();
					}
					catch (IOException e)
					{
					}
				}
			}

		}
		finally
		{
			socket.close();
		}
	}

}
